package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class ModifyUserDialog extends JDialog {
    private final UserManagementFrame parentFrame;
    private final User user;
    private JTextField nameField;
    private JComboBox<String> roleCombo;

    public ModifyUserDialog(UserManagementFrame parent, User user) {
        super(parent, "修改用户信息", true);
        this.parentFrame = parent;
        this.user = user;
        setSize(400, 250);
        setLocationRelativeTo(parent);
        setLayout(null);

        // 用户ID（不可编辑）
        JLabel idLabel = new JLabel("用户ID:");
        idLabel.setBounds(30, 30, 100, 25);
        add(idLabel);

        JTextField idField = new JTextField(user.getId());
        idField.setEditable(false);
        idField.setBounds(130, 30, 220, 25);
        add(idField);

        // 姓名
        JLabel nameLabel = new JLabel("姓名*:");
        nameLabel.setBounds(30, 70, 100, 25);
        add(nameLabel);

        nameField = new JTextField(user.getName());
        nameField.setBounds(130, 70, 220, 25);
        add(nameField);

        // 角色
        JLabel roleLabel = new JLabel("角色*:");
        roleLabel.setBounds(30, 110, 100, 25);
        add(roleLabel);

        roleCombo = new JComboBox<>(new String[]{"student", "teacher", "admin"});
        roleCombo.setSelectedItem(user.getRole());
        roleCombo.setBounds(130, 110, 220, 25);
        add(roleCombo);

        // 按钮
        JButton saveButton = new JButton("保存");
        saveButton.setBounds(100, 160, 100, 30);
        saveButton.addActionListener(this::saveChanges);
        add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.setBounds(220, 160, 100, 30);
        cancelButton.addActionListener(e -> dispose());
        add(cancelButton);
    }

    private void saveChanges(ActionEvent e) {
        String newName = nameField.getText().trim();
        String newRole = (String) roleCombo.getSelectedItem();

        if (newName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "姓名不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 更新用户信息
        user.setName(newName);
        user.setRole(newRole);

        if (UserDAO.updateUser(user)) {
            JOptionPane.showMessageDialog(this, "用户信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            parentFrame.refreshTable(); // 刷新父窗口的表格
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "用户信息更新失败", "失败", JOptionPane.ERROR_MESSAGE);
        }
    }
}